import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, TouchableOpacity, PixelRatio, SectionList } from "react-native";
import { API, API_GENERATE } from '../config/api';
import HTTP from '../utils/http';
import StorageHelper from '../utils/storageHelper';
import { GLOBAL } from '../config/global';
import { style } from '../theme/style';
import { STORAGE_CONSTANT } from '../config/storage';
import { PageStatusIndex } from './page-status/PageStatusIndex';
import { SearchInput } from './SearchInput';

const scale = GLOBAL.SCALE;
const searchLeft = require('../imgs/customer/searchLeft.png');
const ITEM_HEIGHT = 42; //item的高度
const HEADER_HEIGHT = 20;  //分组头部的高度
const SEPARATOR_HEIGHT = 0;  //分割线的高度
const requestObj = {
	keyword: "",
	pageSize: 10,
};

export class CountryListPage extends Component {
	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		const backIcon = require('../imgs/global/backGray.png');
		const backIconStyle = { width: 20 * scale, resizeMode: 'contain', marginLeft: 10 * scale }
		return {
			headerTintColor: '#404040',
			headerTitle: <SearchInput setKeyWord={(txt) => { params.setKeyWord(txt); }}
				onChangeText={() => { params.doSearch(); }}
				onSubmitEditing={() => { params.doSearch(); }}
				placeholder='搜索国家'
				inputLeftIcon={searchLeft} />,
			headerRight: (
				<Text style={{ marginRight: 10 * scale, fontSize: 12 * scale, color: '#404040' }} onPress={() => { params.doSearch() }}>搜索</Text>
			),
			headerLeft: <TouchableOpacity onPress={() => navigation.goBack()} activeOpacity={0.5}><Image source={backIcon} style={backIconStyle} /></TouchableOpacity>,
			headerStyle: {
				elevation: 0,
				borderBottomWidth: 1,
				borderBottomColor: '#E4E4E4',
				backgroundColor: '#fff',
			},
		};
	}

	constructor(props) {
		super(props);
		this.state = {
			countryInfo: {},
			charKeys: [],  //侧边字母
			pageStatus: {
				status: 'loading'
			},
			checkChar: null
		}

		this._setKeyWord = this._setKeyWord.bind(this);
		this._doSearch = this._doSearch.bind(this);
		this.paramCity = '';
		//requestObj.keyword = curCity;
		//this.curCity = curCity;
		this.charOffset = {};
	}

	componentWillMount () {
		this._getCountryInfo();
	}

	componentDidMount () {
		// requestObj.companyName = '';
		this.props.navigation.setParams({
			doSearch: this._doSearch,
			setKeyWord: this._setKeyWord
		});
	}

	componentWillUnmount () {
		this.timer && clearTimeout(this.timer);
	}

	/**
	 * 设置搜索关键字
	 * @param {String} txt 
	 */
	_setKeyWord (txt) {
		requestObj.keyword = txt;
	}

	async _doSearch () {
		const { allCountry } = this.state;
		const filterCity = {};
		const keyword = requestObj.keyword.replace(/市/g, '');
		for (let key in allCountry) {
			if (allCountry[key] && allCountry[key].length > 0) {
				filterCity[key] = [];
				allCountry[key].filter(item => {
					const { areaName, pinyin } = item;
					if (areaName.includes(keyword) || pinyin.toUpperCase().includes(keyword.toUpperCase())) {
						filterCity[key].push(item);
					}
				});
			}
		}
		this.setState({ countryInfo: filterCity });
	}


	async _getCountryInfo () {
		//获取
		const { countryInfo } = this.props.navigation.state.params;
		let data;
		if (countryInfo) {
			data = countryInfo;
		} else {
			this.setState({
				pageStatus: {
					status: 'loading'
				}
			})

			data = await this._getCountryList();
		}

		if (data) {
			this.setState({
				countryInfo: data,
				allCountry: data,
				pageStatus: {
					status: 'data'
				}
			})
		} else {
			this.setState({
				countryInfo: data,
				allCountry: data,
				pageStatus: {
					status: 'error'
				}
			})
		}
	}

	async _getCountryList () {
		const countryInfo = await HTTP.GET(API_GENERATE(API.GET_AREA_LIST_BY_LEVEL) + '?nodeLevel="1"');

		if (countryInfo) {
			StorageHelper.set(STORAGE_CONSTANT.COUNTRY_INFO, countryInfo);
		}

		return countryInfo;
	}

	_cell (data) {
		const sectionItem = data.item;

		return (
			<TouchableOpacity style={styles.item}
				activeOpacity={0.5} onPress={() => {
					//选择城市
					const { navigate } = this.props.navigation;
					navigate('EnterpriseCreateBaseInfo', {
						checkCountryInfo: sectionItem
					});
				}}>
				<View style={styles.right}>
					<Text style={styles.content}>{sectionItem.areaName}</Text>
				</View>
			</TouchableOpacity>

		)
	}

	_header (header) {
		return (
			<View style={styles.titleContainer}
				ref={view => {
					this.charOffset[`ref${header.section.name}`] = view;
				}}>
				<Text style={styles.title}>{header.section.name}</Text>
			</ View>
		)
	}

	_getItemLayout (data, index) {
		let [length, separator, header] = [ITEM_HEIGHT, SEPARATOR_HEIGHT, HEADER_HEIGHT];
		return { length, offset: (length + separator) * index + header, index };
	}
	render () {
		const { navigate } = this.props.navigation;
		const { pageStatus, countryInfo, checkChar } = this.state;
		const sections = [];
		const charKeys = [];
		let chinaItem = {};
		if (countryInfo) {
			for (let key in countryInfo) {
				if (countryInfo[key] && countryInfo[key].length > 0) {
					charKeys.push({ key: key.toUpperCase() });
					sections.push({ key: key.toUpperCase(), name: key.toUpperCase(), data: countryInfo[key] });
					if (key.toUpperCase() === 'Z') {
						countryInfo[key].map((item, index) => {
							if (item.areaId === '86') {
								chinaItem = item;
							}
						})
					}
				}
			}
			sections.unshift({ key: '', name: '', data: [chinaItem] });
		}
		return (
			<View style={{ flex: 1 }}>
				{
					pageStatus.status === 'data' ?
						<View style={styles.container}>
							{
								charKeys.length && charKeys.length > 0 ?
									(
										<View style={styles.list}>
											<SectionList
												ref={ref => this.sectionList = ref}
												sections={sections}//数据源
												renderItem={this._cell.bind(this)}//cell绑定时间创建cell
												keyExtractor={(item, index) => index}//去除警告
												renderSectionHeader={this._header.bind(this)}//Header绑定时间创建表头
												scrollEnabled={true}//默认是true，false禁止滚动
												refreshing={false}
												onRefresh={() => { this._getCountryList.bind(this) }}
												getItemLayout={this._getItemLayout.bind(this)}
											/>
										</View>
									) : (
										<View style={styles.noMatch}>
											<Text style={styles.noMatchText}>没有查询到该国家</Text>
										</View>
									)
							}
						</View>
						: (<PageStatusIndex {...pageStatus} />)   //页面状态
				}
				{
					//点击字母提示
					checkChar ?
						(<View style={styles.charTipBox}>
							<View style={styles.charTip}>
								<Text style={styles.charTipText}>{checkChar}</Text>
							</View>
						</View>)
						: (null)
				}
				{
					//侧边字母栏
					charKeys.length && charKeys.length > 0 ?
						(
							<View style={styles.charCotainer}>
								<Image style={styles.charImg} source={require('../imgs/global/blueSearch.png')} />
								{
									charKeys.map((item, index) => {
										return (
											<TouchableOpacity key={index} activeOpacity={0.5} onPress={() => {
												//跳转到指定的索引位置
												this.sectionList.scrollToLocation({
													sectionIndex: index + 1,
													itemIndex: 0,
													viewOffset: 0,
												});
											}}>
												<Text style={styles.charKeys}>{item.key}</Text>
											</TouchableOpacity>
										)
									})
								}
							</View>
						) : (null)
				}
			</View>
		)
	}
}

const styles = StyleSheet.create({
	searchView: {
		paddingLeft: 5 * scale,
		alignItems: 'center',
		flex: 1,
		flexDirection: 'row',
		width: 300 * scale,
		height: 31 * scale,
		backgroundColor: '#F6F6F6',
		borderRadius: 4,
	},
	searchInput: {
		padding: 0,
		flex: 1,
		height: 31 * scale,
		fontSize: 12 * scale,
		color: '#979797',
		marginLeft: 3 * scale,
	},
	searchLeftIcon: {
		height: 13 * scale,
		width: 13 * scale,
		marginLeft: 10 * scale,
		marginRight: 10 * scale,
	},
	searchRightIcon: {
		height: 10 * scale,
		width: 10 * scale,
		marginRight: 10 * scale,
	},
	container: {
		flex: 1,
		backgroundColor: '#fff',
	},
	titleContainer: {
		backgroundColor: '#f6f6f6'
	},
	title: {
		fontSize: 13 * scale,
		color: '#8B8B8B',
		paddingTop: 2 * scale,
		paddingBottom: 2 * scale,
		paddingLeft: 17 * scale
	},
	list: {
		position: 'relative',
	},
	item: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingTop: 14 * scale,
		paddingBottom: 14 * scale,
		marginLeft: 17 * scale,
		marginRight: 22 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: '#e4e4e4'
	},
	content: {
		flex: 1,
		fontSize: 13 * scale,
		color: '#404040'
	},
	right: {
		paddingTop: 4 * scale,
		paddingBottom: 4 * scale
	},
	charCotainer: {
		position: 'absolute',
		top: 116 * scale,
		right: 5 * scale,
	},
	charImg: {
		width: 10 * scale,
		height: 10 * scale,
		marginBottom: 3 * scale,
	},
	charKeys: {
		fontSize: 12 * scale,
		color: style.color.themeColor,
	},
	cityContainer: {
		paddingTop: 14 * scale,
		marginLeft: 17 * scale,
		marginRight: 13 * scale,
	},
	cityLabel: {
		fontSize: 13 * scale,
		color: '#8b8b8b',
		paddingBottom: 14 * scale,
	},
	cityBox: {
		flexDirection: 'row',
		flex: 1,
		flexWrap: 'wrap',
	},
	cityValueCon: {
		width: 105 * scale,
		marginBottom: 12 * scale,
		paddingTop: 9 * scale,
		paddingBottom: 9 * scale,
		backgroundColor: '#F6F6F6',
		borderRadius: 67 * scale,
		alignItems: 'center',
		marginRight: 9 * scale
	},
	cityValue: {
		fontSize: 13 * scale,
		color: '#4B4B4B',
	},
	noMatch: {
		flex: 1,
		alignItems: 'center',
		paddingTop: 15 * scale
	},
	noMatchText: {
		fontSize: 14 * scale,
		color: '#4B4B4B',
	},
	charTipBox: {
		position: 'absolute',
		top: 120 * scale,
		width: '100%',
		justifyContent: 'center',
		alignItems: 'center',
	},
	charTip: {
		width: 50 * scale,
		height: 50 * scale,
		backgroundColor: 'rgba(0,0, 0, .3)',
		borderRadius: 7,
		justifyContent: 'center',
		alignItems: 'center',
	},
	charTipText: {
		fontSize: 18 * scale,
		color: '#fff',
	}
})